import logging, time
from page_object_demo.Common.function import project_path

class Log:
    """
    基础日志类
    """
    def __init__(self, tag, level=logging.DEBUG, path=None):
        """若有指定日志保存路径path，则会在输出日志时同时保存一份日志到本地指定目录下"""
        self.logger = logging.getLogger(tag)
        self.logger.setLevel(level)
        self.level = level
        self.path = path
        self.__format_log()
        self.init_log()

    def __format_log(self):
        fmt = logging.Formatter("%(asctime)s %(module)s.%(name)s.%(funcName)s %(lineno)d [%(levelname)s] - %(message)s")
        if self.path is not None:
            # 若有指定日志保存路径path，则会在输出日志时同时保存一份日志到本地指定目录下
            handler = logging.FileHandler(filename=self.path, mode="a", encoding="utf-8")
            handler.setFormatter(fmt)
            handler.setLevel(self.level)
            self.logger.addHandler(handler)

        sys_handler = logging.StreamHandler()
        sys_handler.setFormatter(fmt)
        sys_handler.setLevel(self.level)
        self.logger.addHandler(sys_handler)

    def init_log(self):
        # 打印info级别的日志
        self.i = self.logger.info
        # 打印debug级别的日志
        self.d = self.logger.debug
        # 打印error级别的日志
        self.e = self.logger.error
        # 打印warning级别的日志
        self.w = self.logger.warning
        # 打印critical级别的日志
        self.c = self.logger.critical


class ADemo:
    """
        一个测试日志收集的类
    """
    def __init__(self, a, b):
        self.a = a
        self.b = b
        path = project_path() + "/Logs/log_outputs/" + time.strftime("%Y_%m_%d_%H_%M_%S") + "_log.log"
        self.log = Log("ADemo", logging.DEBUG, path=path)
        # 获取当前的引用类型名
        # a=str(self.__class__)
        # start = a.rfind(".")
        # print(a[start + 1:-2])

    def add(self):
        result = self.a + self.b
        self.log.d("ademo.add()={0}".format(result))
        return result


if __name__ == '__main__':
    path = project_path() + "/Logs/log_outputs/" + time.strftime("%Y_%m_%d_%H_%M_%S") + "_log.log"
    log = Log("ADemo", logging.DEBUG, path=path)
    ademo = ADemo(1, 2)
    ademo.add()
    log.i("this is a info demo")
    log.e("this is a error demo")
    log.c("this is a critical demo")
    log.w("this is a waring demo")
